package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.sys.SysUploadExcelDao;
import com.framework.entity.sys.SysTemplate;
import com.framework.entity.sys.SysUploadExcel;
import com.framework.page.PageUtils;
import com.framework.page.Query;
import com.framework.service.SysTemplateService;
import com.framework.service.SysUploadExcelService;
import com.framework.validator.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service("sysUploadService")
public class SysUploadExcelServiceImpl extends ServiceImpl<SysUploadExcelDao, SysUploadExcel> implements SysUploadExcelService {

    @Autowired
    private SysTemplateService sysTemplateService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Long deptId = (Long) params.get("deptId");
        Page<SysUploadExcel> page = selectPage(new Query<SysUploadExcel>(params).getPage(),
                new EntityWrapper<SysUploadExcel>()
                        .where(!deptId.equals(1L), " FIND_IN_SET({0},dept_id)", deptId));
        return new PageUtils(page);
    }

    @Override
    public void save(SysUploadExcel sysUploadExcel) {
        String[] ids = sysUploadExcel.getDeptIds();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < ids.length; i++) {
            String id = ids[i];
            stringBuilder.append(i == ids.length - 1 ? id : (id + ","));
        }
        sysUploadExcel.setDeptId(stringBuilder.toString());
        sysUploadExcel.setCreateTime(new Date());
        baseMapper.insert(sysUploadExcel);
    }

    @Override
    public void modify(SysUploadExcel sysUploadExcel) {
        String[] ids = sysUploadExcel.getDeptIds();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < ids.length; i++) {
            String id = ids[i];
            stringBuilder.append(i == ids.length - 1 ? id : (id + ","));
        }
        sysUploadExcel.setDeptId(stringBuilder.toString());
        updateById(sysUploadExcel);
    }

    @Override
    public String getTemplate(Integer templateType, Long deptId) {

        SysTemplate sysTemplate = sysTemplateService.queryByTypeAndDeptId(templateType, deptId);

        Assert.isNull(sysTemplate, "暂无模板");
        return sysTemplate.getUrl();
    }

}
